import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import '../models/app_state.dart';
import '../models/note.dart';

/**
 * 笔记编辑器组件
 * 支持 Markdown 编辑和预览
 */
class NoteEditor extends StatefulWidget {
  const NoteEditor({super.key});

  @override
  State<NoteEditor> createState() => _NoteEditorState();
}

class _NoteEditorState extends State<NoteEditor> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _contentController = TextEditingController();
  final FocusNode _titleFocusNode = FocusNode();
  final FocusNode _contentFocusNode = FocusNode();
  
  bool _isPreviewMode = false;
  Note? _currentNote;

  @override
  void initState() {
    super.initState();
    _titleController.addListener(() async {
      await _saveNote();
    });
    
    _contentController.addListener(() async {
      await _saveNote();
    });
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _titleFocusNode.dispose();
    _contentFocusNode.dispose();
    super.dispose();
  }

  /**
   * 保存笔记
   */
  Future<void> _saveNote() async {
    if (_currentNote == null) return;

    final updatedNote = _currentNote!.copyWith(
      title: _titleController.text.trim().isEmpty 
          ? '无标题' 
          : _titleController.text.trim(),
      content: _contentController.text,
      updatedAt: DateTime.now(),
    );

    await context.read<AppState>().updateNote(updatedNote);
  }

  /**
   * 监听笔记变化
   */
  void _onNoteChanged(Note? note) {
    if (note != _currentNote) {
      // 保存当前笔记
      if (_currentNote != null) {
        _saveNote();
      }

      // 切换到新笔记
      _currentNote = note;
      if (note != null) {
        _titleController.text = note.title;
        _contentController.text = note.content;
      } else {
        _titleController.clear();
        _contentController.clear();
      }
    }
  }

  /**
   * 插入 Markdown 格式
   */
  void _insertMarkdown(String prefix, [String suffix = '']) {
    final text = _contentController.text;
    final selection = _contentController.selection;
    
    if (selection.isValid) {
      final selectedText = text.substring(selection.start, selection.end);
      final newText = text.replaceRange(
        selection.start,
        selection.end,
        '$prefix$selectedText$suffix',
      );
      
      _contentController.text = newText;
      _contentController.selection = TextSelection.collapsed(
        offset: selection.start + prefix.length + selectedText.length + suffix.length,
      );
    } else {
      final newText = text + prefix + suffix;
      _contentController.text = newText;
      _contentController.selection = TextSelection.collapsed(
        offset: newText.length - suffix.length,
      );
    }
    
    _contentFocusNode.requestFocus();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            colorScheme.surface,
            colorScheme.surface.withOpacity(0.95),
          ],
        ),
      ),
      child: Consumer<AppState>(
        builder: (context, appState, child) {
          _onNoteChanged(appState.currentNote);
          
          if (appState.currentNote == null) {
            return Center(
              child: Container(
                padding: const EdgeInsets.all(32),
                decoration: BoxDecoration(
                  color: colorScheme.surfaceVariant.withOpacity(0.3),
                  borderRadius: BorderRadius.circular(24),
                  border: Border.all(
                    color: colorScheme.outline.withOpacity(0.1),
                    width: 1,
                  ),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: colorScheme.primary.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Icon(
                        Icons.edit_note,
                        size: 48,
                        color: colorScheme.primary,
                      ),
                    ),
                    const SizedBox(height: 24),
                    Text(
                      '选择一篇笔记开始编辑',
                      style: theme.textTheme.titleLarge?.copyWith(
                        color: colorScheme.onSurface,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '或者创建一篇新的笔记',
                      style: theme.textTheme.bodyMedium?.copyWith(
                        color: colorScheme.onSurfaceVariant,
                      ),
                    ),
                    const SizedBox(height: 24),
                    FilledButton.icon(
                      onPressed: () {
                        appState.createNote();
                      },
                      icon: const Icon(Icons.add, size: 20),
                      label: const Text('新建笔记'),
                      style: FilledButton.styleFrom(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 24,
                          vertical: 12,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          }

          return Column(
            children: [
              // 工具栏
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: const [
                      Colors.transparent,
                      Colors.transparent,
                    ],
                  ),
                  border: Border(
                    bottom: BorderSide(
                      color: colorScheme.outline.withOpacity(0.1),
                      width: 1,
                    ),
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: colorScheme.shadow.withOpacity(0.05),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: Row(
                  children: [
                    // 标题输入框
                    Expanded(
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                        decoration: BoxDecoration(
                          color: colorScheme.surface.withOpacity(0.8),
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(
                            color: colorScheme.outline.withOpacity(0.1),
                            width: 1,
                          ),
                        ),
                        child: TextField(
                          controller: _titleController,
                          focusNode: _titleFocusNode,
                          decoration: InputDecoration(
                            hintText: '请输入标题...',
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                            hintStyle: theme.textTheme.titleLarge?.copyWith(
                              color: colorScheme.onSurfaceVariant.withOpacity(0.6),
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          style: theme.textTheme.titleLarge?.copyWith(
                            fontWeight: FontWeight.bold,
                            color: colorScheme.onSurface,
                          ),
                          onChanged: (value) {
                            // 实时保存标题
                            if (_currentNote != null) {
                              final updatedNote = _currentNote!.copyWith(
                                title: value.trim(),
                                updatedAt: DateTime.now(),
                              );
                              context.read<AppState>().updateNote(updatedNote);
                            }
                          },
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    
                    // 工具按钮
                    Container(
                      decoration: BoxDecoration(
                        color: colorScheme.surfaceVariant.withOpacity(0.3),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: colorScheme.outline.withOpacity(0.1),
                          width: 1,
                        ),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          // 预览模式切换
                          Container(
                            margin: const EdgeInsets.all(4),
                            decoration: BoxDecoration(
                              color: _isPreviewMode 
                                ? colorScheme.primary.withOpacity(0.1)
                                : Colors.transparent,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: IconButton(
                              onPressed: () {
                                setState(() {
                                  _isPreviewMode = !_isPreviewMode;
                                });
                              },
                              icon: Icon(
                                _isPreviewMode ? Icons.edit : Icons.preview,
                                color: _isPreviewMode 
                                  ? colorScheme.primary
                                  : colorScheme.onSurfaceVariant,
                                size: 20,
                              ),
                              tooltip: _isPreviewMode ? '编辑模式' : '预览模式',
                              padding: const EdgeInsets.all(8),
                              constraints: const BoxConstraints(
                                minWidth: 36,
                                minHeight: 36,
                              ),
                            ),
                          ),
                          
                          // Markdown 工具
                          if (!_isPreviewMode) ...[
                            Container(
                              margin: const EdgeInsets.all(4),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: PopupMenuButton<String>(
                                icon: Icon(
                                  Icons.format_bold,
                                  color: colorScheme.onSurfaceVariant,
                                  size: 20,
                                ),
                                tooltip: 'Markdown 格式',
                                padding: const EdgeInsets.all(8),
                                constraints: const BoxConstraints(
                                  minWidth: 36,
                                  minHeight: 36,
                                ),
                                itemBuilder: (context) => [
                                  PopupMenuItem(
                                    value: 'bold',
                                    child: Container(
                                      padding: const EdgeInsets.symmetric(vertical: 4),
                                      child: Row(
                                        children: [
                                          Icon(
                                            Icons.format_bold, 
                                            size: 18,
                                            color: colorScheme.onSurface,
                                          ),
                                          const SizedBox(width: 12),
                                          Text(
                                            '粗体',
                                            style: theme.textTheme.bodyMedium?.copyWith(
                                              color: colorScheme.onSurface,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  PopupMenuItem(
                                    value: 'italic',
                                    child: Container(
                                      padding: const EdgeInsets.symmetric(vertical: 4),
                                      child: Row(
                                        children: [
                                          Icon(
                                            Icons.format_italic, 
                                            size: 18,
                                            color: colorScheme.onSurface,
                                          ),
                                          const SizedBox(width: 12),
                                          Text(
                                            '斜体',
                                            style: theme.textTheme.bodyMedium?.copyWith(
                                              color: colorScheme.onSurface,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                              const PopupMenuItem(
                                value: 'code',
                                child: Row(
                                  children: [
                                    Icon(Icons.code, size: 16),
                                    SizedBox(width: 8),
                                    Text('代码'),
                                  ],
                                ),
                              ),
                              const PopupMenuItem(
                                value: 'link',
                                child: Row(
                                  children: [
                                    Icon(Icons.link, size: 16),
                                    SizedBox(width: 8),
                                    Text('链接'),
                                  ],
                                ),
                              ),
                              const PopupMenuItem(
                                value: 'image',
                                child: Row(
                                  children: [
                                    Icon(Icons.image, size: 16),
                                    SizedBox(width: 8),
                                    Text('图片'),
                                  ],
                                ),
                              ),
                              const PopupMenuDivider(),
                              const PopupMenuItem(
                                value: 'h1',
                                child: Text('# 标题 1'),
                              ),
                              const PopupMenuItem(
                                value: 'h2',
                                child: Text('## 标题 2'),
                              ),
                              const PopupMenuItem(
                                value: 'h3',
                                child: Text('### 标题 3'),
                              ),
                              const PopupMenuDivider(),
                              const PopupMenuItem(
                                value: 'list',
                                child: Row(
                                  children: [
                                    Icon(Icons.format_list_bulleted, size: 16),
                                    SizedBox(width: 8),
                                    Text('列表'),
                                  ],
                                ),
                              ),
                              const PopupMenuItem(
                                value: 'quote',
                                child: Row(
                                  children: [
                                    Icon(Icons.format_quote, size: 16),
                                    SizedBox(width: 8),
                                    Text('引用'),
                                  ],
                                ),
                              ),
                                ],
                                onSelected: (value) {
                                  switch (value) {
                                    case 'bold':
                                      _insertMarkdown('**', '**');
                                      break;
                                    case 'italic':
                                      _insertMarkdown('*', '*');
                                      break;
                                    case 'code':
                                      _insertMarkdown('`', '`');
                                      break;
                                    case 'link':
                                      _insertMarkdown('[', '](url)');
                                      break;
                                    case 'image':
                                      _insertMarkdown('![', '](url)');
                                      break;
                                    case 'h1':
                                      _insertMarkdown('# ');
                                      break;
                                    case 'h2':
                                      _insertMarkdown('## ');
                                      break;
                                    case 'h3':
                                      _insertMarkdown('### ');
                                      break;
                                    case 'list':
                                      _insertMarkdown('- ');
                                      break;
                                    case 'quote':
                                      _insertMarkdown('> ');
                                      break;
                                  }
                                },
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              
              // 编辑区域
              Expanded(
                child: _isPreviewMode
                    ? _buildPreviewArea()
                    : _buildEditArea(),
              ),
            ],
          );
        },
      ),
    );
  }

  /**
   * 构建编辑区域
   */
  Widget _buildEditArea() {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: colorScheme.outline.withOpacity(0.1),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: colorScheme.shadow.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: TextField(
        controller: _contentController,
        focusNode: _contentFocusNode,
        maxLines: null,
        expands: true,
        decoration: InputDecoration(
          hintText: '开始写作...',
          hintStyle: theme.textTheme.bodyLarge?.copyWith(
            color: colorScheme.outline.withOpacity(0.6),
            height: 1.6,
          ),
          border: InputBorder.none,
          contentPadding: EdgeInsets.zero,
        ),
        style: theme.textTheme.bodyLarge?.copyWith(
          height: 1.6,
          color: colorScheme.onSurface,
        ),
        cursorColor: colorScheme.primary,
        onChanged: (value) {
          // 实时保存内容
          if (_currentNote != null) {
            final updatedNote = _currentNote!.copyWith(
              content: value,
              updatedAt: DateTime.now(),
            );
            context.read<AppState>().updateNote(updatedNote);
          }
        },
      ),
    );
  }

  /**
   * 构建预览区域
   */
  Widget _buildPreviewArea() {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: colorScheme.outline.withOpacity(0.1),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: colorScheme.shadow.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: _contentController.text.isEmpty 
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.preview,
                    size: 48,
                    color: colorScheme.outline.withOpacity(0.5),
                  ),
                  const SizedBox(height: 16),
                  Text(
                    '暂无内容',
                    style: theme.textTheme.titleMedium?.copyWith(
                      color: colorScheme.outline,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '在编辑模式下输入内容后可在此预览',
                    style: theme.textTheme.bodyMedium?.copyWith(
                      color: colorScheme.outline.withOpacity(0.7),
                    ),
                  ),
                ],
              ),
            )
          : SingleChildScrollView(
              child: Markdown(
                data: _contentController.text,
                selectable: true,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                styleSheet: MarkdownStyleSheet(
                  p: theme.textTheme.bodyLarge?.copyWith(
                    height: 1.6,
                    color: colorScheme.onSurface,
                  ),
                  h1: theme.textTheme.headlineMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                    color: colorScheme.onSurface,
                    height: 1.3,
                  ),
                  h2: theme.textTheme.headlineSmall?.copyWith(
                    fontWeight: FontWeight.bold,
                    color: colorScheme.onSurface,
                    height: 1.3,
                  ),
                  h3: theme.textTheme.titleLarge?.copyWith(
                    fontWeight: FontWeight.bold,
                    color: colorScheme.onSurface,
                    height: 1.3,
                  ),
                  h4: theme.textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface,
                  ),
                  h5: theme.textTheme.titleSmall?.copyWith(
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface,
                  ),
                  h6: theme.textTheme.labelLarge?.copyWith(
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface,
                  ),
                  code: TextStyle(
                    backgroundColor: colorScheme.surfaceVariant.withOpacity(0.8),
                    color: colorScheme.onSurfaceVariant,
                    fontFamily: 'Consolas',
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                  codeblockDecoration: BoxDecoration(
                    color: colorScheme.surfaceVariant.withOpacity(0.5),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: colorScheme.outline.withOpacity(0.1),
                      width: 1,
                    ),
                  ),
                  codeblockPadding: const EdgeInsets.all(16),
                  blockquote: theme.textTheme.bodyLarge?.copyWith(
                    color: colorScheme.onSurfaceVariant,
                    fontStyle: FontStyle.italic,
                    height: 1.6,
                  ),
                  blockquoteDecoration: BoxDecoration(
                    color: colorScheme.surfaceVariant.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(8),
                    border: Border(
                      left: BorderSide(
                        color: colorScheme.primary,
                        width: 4,
                      ),
                    ),
                  ),
                  blockquotePadding: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 12,
                  ),
                  listBullet: theme.textTheme.bodyLarge?.copyWith(
                    color: colorScheme.primary,
                    fontWeight: FontWeight.bold,
                  ),
                  tableHead: theme.textTheme.titleSmall?.copyWith(
                    fontWeight: FontWeight.bold,
                    color: colorScheme.onSurface,
                  ),
                  tableBody: theme.textTheme.bodyMedium?.copyWith(
                    color: colorScheme.onSurface,
                  ),
                  tableBorder: TableBorder.all(
                    color: colorScheme.outline.withOpacity(0.2),
                    width: 1,
                  ),
                  tableCellsPadding: const EdgeInsets.all(12),
                  a: TextStyle(
                    color: colorScheme.primary,
                    decoration: TextDecoration.underline,
                    decorationColor: colorScheme.primary.withOpacity(0.5),
                  ),
                ),
              ),
            ),
    );
  }
}